import { useState, useRef } from 'react';


/**
 * 函数节流
 * @param func 节流函数 
 * @param duration 节流时间
 */
export const useThrottle = (func: Function | undefined, duration: number = 1000) => {
    /** 节流时间 */
    const [delayTime, setDelayTime] = useState<number>(duration);
    /** 节流时间对象 */
    const timer = useRef<any>(null);
    /** 节流回调函数 */
    const throttleFunc = (...args: Array<any>) => {
        if (!timer.current) {
            func(...args);
            timer.current = setTimeout(() => {
                clearTimeout(timer.current);
                timer.current = null;
            }, delayTime);
        }
    }
    /** 清除节流 */
    const clearThrottleFunc = () => setDelayTime(0);
    return { throttleFunc, clearThrottleFunc }
}